package hku.cs.lunuo.run;

import hku.cs.instrument.Instrument;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import soot.options.Options;

public class SocketRunner {
	private int port;
	private Socket socket;
	private PrintWriter writer;
	
	public static void main(String[] args) {
		new SocketRunner().run(args);
	}

	private void run(String[] args) {
		try {
			Thread.currentThread().sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		try {
			Options.v().set_keep_line_number(true);
		
			String[] klasses = args[1].split(";");
//			String[] csses = new String[klasses.length+2];
//			csses[0] = "-src-prec";
//			csses[1] = "java";
//			int i = 2;
//			for(String klass : klasses){
//				csses[i] = klass;
//				i++;
//			}
//			
//			soot.Main.main(csses);
//			
//			
//			try {
//				Thread.currentThread().sleep(100);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			soot.G.reset();
			Options.v().set_output_dir(args[0]);			
			Instrument.main(klasses);
			
		} finally {
			closeClientSocket();
		}
			

//		try {
//			File f = new File(args[1]+File.separator+"dirty.lu");
//			BufferedReader br = new BufferedReader(new FileReader(f));
//			String line;
//			String[] mainArgs = new String[2];
//			mainArgs[0] = "C:\\xujian";
//			while((line=br.readLine())!=null){
//				mainArgs[1] = line;
//				mainArgs[1] = "Y87675";
//				System.out.print(args);	
//				File fy = new File("C:\\xujian\\dirty.txt");
//				FileWriter fw;
//				try {
//					fw =new FileWriter(fy,true);
//					fw.append("1");
//					fw.close();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				hku.cfg.Class.main(args);
//			}
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} finally {
//			closeClientSocket();
//		}
	}

	private void openClientSocket() {
		for (int i= 0; i < 10; i++) {
			try {
				socket= new Socket("localhost", port);
				writer= new PrintWriter(socket.getOutputStream(), true);
				return;
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
			}
		}

		
	}
	
	private void closeClientSocket() {
		if(writer!=null)
			writer.close();
		try {
			if(socket!=null)
				socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}